package org.slf4j.impl;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

public abstract class XtraTinyLoggerAppender {
	private static final int DEFAULT_CAPACITY = 4096;

	private BlockingQueue<String> queue;
	private QueueProcessor queueProcessorThread;

	private class QueueProcessor extends Thread {
		public void run() {
			try {
				String msg;
				while (!Thread.currentThread().isInterrupted()) {
					msg = queue.take();
					processMessage(msg);
				}
			} catch (InterruptedException e) {
				;
			}
		}

		public void shutdown() {
			this.interrupt();
			String msg;
			while ((msg = queue.poll()) != null) {
				processMessage(msg);
			}
			XtraTinyLoggerAppender.this.shutdown();
		}
	}

	public XtraTinyLoggerAppender() {
		queue = new LinkedBlockingQueue<String>(DEFAULT_CAPACITY);
		queueProcessorThread = new QueueProcessor();
		queueProcessorThread.setDaemon(true);
		queueProcessorThread.start();
	}

	public void append(String msg) {
		queue.offer(msg);
	}

	public void close() {
		queueProcessorThread.shutdown();
	}

	protected abstract void processMessage(String msg);

	protected abstract void shutdown();
}
